package com.zhidao.backend.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhidao.backend.common.CommentToRouteRequest;
import com.zhidao.backend.common.StatusCode;
import com.zhidao.backend.entity.Comment;
import com.zhidao.backend.exception.BusinessException;
import com.zhidao.backend.mapper.CommentMapper;
import com.zhidao.backend.service.ICommentService;
import org.jetbrains.annotations.NotNull;
import org.springframework.stereotype.Service;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class CommentServiceImpl extends ServiceImpl<CommentMapper, Comment> implements ICommentService {
    @Override
    public Long commentToRoute(@NotNull CommentToRouteRequest commentToRouteRequest) {
        Long commentatorId = commentToRouteRequest.getCommentatorId();
        Long routeId= commentToRouteRequest.getRouteId();
        String commentLines = commentToRouteRequest.getCommentLines();
        Comment comment = new Comment();
        comment.setRouteId(routeId);
        comment.setUserId(commentatorId);
        comment.setCommentLines(commentLines);
        List<Comment> commentList=this.list(new QueryWrapper<Comment>().eq("route_id",routeId).orderByDesc("floor"));
        if (commentList.size() == 0) {
            comment.setFloor(1);
        } else {
            Integer maxFloor=commentList.get(0).getFloor();
            comment.setFloor(maxFloor+1);
        }
        Date date = new Date();
        Timestamp timestamp = new Timestamp(date.getTime());
        comment.setCommentTime(timestamp);
        int res = baseMapper.insert(comment);
        if (res < 1) {
            throw new BusinessException(StatusCode.SYSTEM_ERROR.getCode(), "评论失败，请重试");
        }
        return comment.getId();
    }

    @Override
    public List<Comment> getCommentList(Long routeId) {
        List<Comment> commentList =  baseMapper.selectList(new QueryWrapper<Comment>().eq("route_id", routeId).orderByDesc("floor"));
        if (commentList == null) {
            return null;
        }
        List<Long> commentIdList = new ArrayList<>();
        for (Comment comment : commentList) {
            commentIdList.add(comment.getId());
        }
        return commentList;
    }

    @Override
    public void deleteComment(Long commentId) {
        int res = baseMapper.deleteById(commentId);
        if (res < 1) {
            throw new BusinessException(StatusCode.SYSTEM_ERROR.getCode(), "删除失败，请重试");
        }
    }

    @Override
    public Comment getCommentById(Long commentId) {
        Comment comment = baseMapper.selectById(commentId);
        if (comment == null) {
            throw new BusinessException(StatusCode.SYSTEM_ERROR.getCode(), "获取评论失败，请重试");
        }
        return comment;
    }

}
